package edu.rpi.tw.escience.stargazer.rest;

import edu.rpi.tw.escience.stargazer.server.SimpleException;
import edu.rpi.tw.escience.stargazer.server.StarGazerContext;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.Rio;
import org.restlet.data.MediaType;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Author: josh
 * Date: Apr 27, 2009
 * Time: 10:56:24 PM
 */
public class CelestialObjectRDFRepresentation extends CelestialObjectRepresentation {
    public CelestialObjectRDFRepresentation(final URI resourceURI,
                                            final StarGazerContext context) {
        super(resourceURI, context, MediaType.APPLICATION_RDF_XML);
    }

    @Override
    public void write(final OutputStream out) throws IOException {
        RDFWriter writer = Rio.createWriter(RDFFormat.RDFXML, out);

        try {
            writer.startRDF();
            for (Statement st : getStatementsAbout()) {
                writer.handleStatement(st);
            }
            writer.endRDF();
        } catch (RepositoryException e) {
            new SimpleException(e).logError();
            throw new IOException("failed to serialize resource");
        } catch (RDFHandlerException e) {
            new SimpleException(e).logError();
            throw new IOException("failed to serialize resource");
        }
    }
}